package com.icoolkj.learn.juc.base.communication;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

/**
 * @author icoolkj
 * @version 1.0
 * @description 管道输入输出流例子
 * @createDate 2025/03/05 11:33
 */
public class PipedDemo {
    public static void main(String[] args) {
        PipedWriter out = new PipedWriter();
        PipedReader in = new PipedReader();

        try {
            // 将输出流和输入流进行连接，否则使用时会抛出 IOException
            out.connect(in);

            Thread printThread = new Thread(new Print(in), "PrintThread");
            printThread.start();

            int receive = 0;
            try {
                // 读取键盘输入流
                while ((receive = System.in.read()) != -1) {
                    // 写入管道
                    out.write(receive);
                }
            } finally {
                out.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    static class Print implements Runnable {
        private PipedReader in;
        public Print(PipedReader in) {
            this.in = in;
        }

        public void run() {
            int receive = 0;
            try{
                // 读取管道输出流
                while ((receive = in.read()) != -1) {
                    System.out.print((char)receive);
                }
            } catch (IOException e){
                e.printStackTrace();
            }
        }

    }
}
